package com.corpgovernment.common.logging;

import com.corpgovernment.common.enums.LogLevelEnum;
import com.corpgovernment.common.util.ThreadPoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @program: corpgovernment-common-logging
 * @description: 日志工具类
 * @author: wubing
 * @create: 2019-06-04 14:54
 */
@Slf4j
public class LogUtil {


    /**
     * 日志打印
     *
     * @param levelEnum 日志级别
     * @param cla       调用class
     * @param title     日志title
     * @param message   日志信息
     * @param tagMaps   日志tag
     */
    public static void logging(LogLevelEnum levelEnum, Class<?> cla, String title, String message, Map<String, String> tagMaps) {
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(tagMaps)) {
            for (String key : tagMaps.keySet()) {
                sb.append(String.format("%s=%s\n", key, tagMaps.get(key)));
            }
        }
        String str = String.format("【类】\n%s\n【信息】\n%s\n", cla, message);
        sb.append(str);
        String var1 = title + "日志打印：\n{}";
        ThreadPoolService.getInstance().writeLog(levelEnum, var1, sb.toString());
        //ThreadPoolService.getInstance().writeCtripLog(levelEnum, title, str, tagMaps);

    }

    public static String getException(Exception ex) {
        if (ex == null) {
            return "";
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = null;
        try {
            ret = new String(out.toByteArray(), "utf-8");
        } catch (UnsupportedEncodingException e) {
        }
        try {
            pout.close();
            out.close();
        } catch (IOException e) {
        } finally {
            try {
                pout.close();
                out.close();
            } catch (Exception x) {

            }
        }
        return ret;
    }
}